Ext.onReady(function(){
    Ext.QuickTips.init();
    Ext.BLANK_IMAGE_URL = 'ext3.2/resources/images/default/s.gif';
    var gridTitle = '功能管理';
    var findall = "appFunction_all.do";
    var addMsg = 'appFunction_add.do';
    var deleteMsg = 'appFunction_delete.do';
    var modifyMsg = 'appFunction_modify.do';
    
    var renderTo = 'appfunction_grid';
    var seqValue = "app_function_seq"; //序列号名称
    var identityName = "functionId"; //主键名称
    var pageSize = 18;
    var gridHeight = 500;
    
    var sm = new Ext.grid.CheckboxSelectionModel();
    var cm = new Ext.grid.ColumnModel([sm, {
        header: "编号",
        width: 100,
        dataIndex: 'functionId'
    }, {
        header: "功能地址",
        width: 100,
        sortable: true,
        dataIndex: 'funKey',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "功能名称",
        width: 100,
        dataIndex: 'funName',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "父类ID",
        width: 100,
        dataIndex: 'parentId',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "菜单等级",
        width: 100,
        dataIndex: 'functionLayer',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "排序",
        width: 100,
        dataIndex: 'functionOrder',
        editor: {
            xtype: 'textfield'
        }
    }]);
    
    var Dict = Ext.data.Record.create([{
        name: 'functionId',
        type: 'int'
    }, {
        name: 'funKey',
        type: 'string'
    }, {
        name: 'funName',
        type: 'string'
    }, {
        name: 'parentId',
        type: 'int'
    }, {
        name: 'functionLayer',
        type: 'int'
    }, {
        name: 'functionOrder',
        type: 'int'
    }]);
    
    var reader = new Ext.data.JsonReader({
        root: 'rows', //rows : 为服务器端传送过来的记录数值对象
        totalProperty: 'total' //results 为服务器端json传送过来的记录的行数, count(*)运算
    }, ['functionId', 'funKey', 'funName', 'parentId', 'functionLayer', 'functionOrder']);
    
    var saveHandler = function(e){
        var conn = new Ext.data.Connection();
        conn.request({
            url: modifyMsg,
            params: {
                'appFunction.functionId': e.record.get("functionId"),
                'appFunction.funKey': e.record.get("funKey"),
                'appFunction.funName': e.record.get("funName"),
                'appFunction.parentId': e.record.get("parentId"),
                'appFunction.functionLayer': e.record.get("functionLayer"),
                'appFunction.functionOrder': e.record.get("functionOrder")
            },
            success: function(resp, opt){
            },
            failure: function(resp, opt){
				Ext.Msg.alert("错误","修改失败");
            }
        });
    }
    //add handle to deal with add action
    var addHandler = function(e){
        var conn = new Ext.data.Connection();
        conn.request({
            url: addMsg,
            params: {
                seqName: seqValue
            },
            success: function(resp, opt){
                var newId = Ext.util.JSON.decode(resp.responseText).newId;
                grid.getStore().insert(0, new Dict({
                    functionId: newId,
                    funKey: '',
                    funName: '',
                    parentId: 0,
                    functionLayer: 0,
                    functionOrder: 0
                }));
            },
            failure: function(resp, opt){
                Ext.Msg.alert('错误', '添加失败！');
            }
        })
    };
    //-------------------------下面无需改动-----------------------------------------------------------
    
    var store = new Ext.data.Store({
        url: findall,
        reader: reader
    });
    store.load({
        params: {
            start: 0,
            limit: pageSize
        }
    });
    
    var editor = new Ext.ux.grid.RowEditor({
        saveText: '保存',
        cancelText: '取消',
        listeners: {
            afteredit: function(e){
                saveHandler(e);
            }
        }
    });
    
    var grid = new Ext.grid.GridPanel({
        renderTo: renderTo,
        frame: true,
        title: gridTitle,
        autoScroll: true,
        width: "auto",
        height: gridHeight,
        store: store,
        plugins: [editor],
        sm: sm,
        cm: cm,
        tbar: [{
            text: ' 增加 ',
            handler: function(e){
                addHandler(e)
            } //deal add
        }, {
            ref: '../removeBtn',
            text: ' 删除 ',
            disabled: true,
            handler: function(e){
                delHandler(e)
            } //处理删除函数 
        }],
        viewConfig: {
            columnsText: "显示/隐藏列",
            sortAscText: "正序排列",
            sortDescText: "倒序排列"
        },
        bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: store,
            displayInfo: true,
            afterPageText: ' 共 {0} 页',
            beforePageText: '页 ',
            firstText: '第一页 ',
            prevText: '前一页',
            nextText: '下一页',
            lastText: '最后一页',
            refreshText: '刷新',
            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg: "没有记录"
        })
    
    });
    
    grid.getSelectionModel().on('selectionchange', function(sm){
        grid.removeBtn.setDisabled(sm.getCount() < 1);
    });
    
    //删除的处理函数
    var delHandler = function(e){
        editor.stopEditing();
        var s = grid.getSelectionModel().getSelections();
        if (!s) 
            return false;
        Ext.Msg.show({
            title: '删除',
            buttons: Ext.MessageBox.YESNOCANCEL,
            msg: '确认删除？',
            fn: function(btn){
        		if(btn == "no" || btn == "cancel") return;
                var ids = "";
                for (var i = 0; i < s.length; i++) { //要删除的记录ID拼串
                    ids = ids + s[i].get(identityName) + ",";
                }
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteMsg,
                    params: {
                        delIds: ids
                    },
                    success: function(resp, opt){
                        for (var i = 0; i < s.length; i++) { //把store中相应的记录删掉
                            grid.getStore().remove(s[i]);
                        }
                        store.reload();
                    },
                    failure: function(resp, opt){
                        Ext.Msg.alert('错误', '删除记录失败！');
                    }
                });
            }
        });
    }
});
